import scopt.test.common
from scopt.mpu.security.db_registry.handlers import invalidate_token
from scopt.mpu.security.db_registry.handlers import authenticate_login_password
from scopt.mpu.security.db_registry.handlers import flyby_token
from scopt.test.common import DEFAULT_LOGIN
from scopt.test.common import DEFAULT_PASSWORD


class InvalidateToken(scopt.test.common.ScoptTest):
    '''Ivalidate token tests
    MPU should:

    1. test_token_invalidate
        send invalidate token request and test system status
    '''
    def test_token_invalidate(self):
        # 1. send unauthenticated request
        handler = flyby_token.handle
        token = handler.TOKEN()
        token['value'] = 'abc'
        response = self.send_request(self.dummy_request(), token,
                                     pass_interrupts=True)
        self.assertStatus(response, 'INT', 'security.invalid.token')

        # 2. authenticate
        handler = authenticate_login_password.handle
        token = handler.TOKEN()
        token['login'] = DEFAULT_LOGIN
        token['password'] = DEFAULT_PASSWORD
        response = self.send_request(self.dummy_request(), token)
        valid_token = response['resd']['token']

        # 3. send authenticated request
        handler = flyby_token.handle
        token = handler.TOKEN()
        token['value'] = valid_token
        response = self.send_request(self.dummy_request(), token)
        self.assertStatus(response, 'OK')

        # 4. logout
        handler = invalidate_token.handle
        token = handler.TOKEN()
        token['value'] = valid_token
        response = self.send_request(self.dummy_request(), token)
        self.assertStatus(response, 'OK')

        # 5. send unauthenticated request
        handler = flyby_token.handle
        token = handler.TOKEN()
        token['value'] = valid_token
        response = self.send_request(self.dummy_request(), token,
                                     pass_interrupts=True)
        self.assertStatus(response, 'INT', 'security.invalid.token')
